package com.jcfk.eam.service.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.eam.dao.base.EamFaultModeAssetDao;
import com.jcfk.eam.domain.dto.base.EamAssetTypeDTO;
import com.jcfk.eam.domain.dto.base.EamFaultModeAssetDTO;
import com.jcfk.eam.domain.po.base.EamFaultModeAsset;
import com.jcfk.eam.domain.po.main.EamAssetStatusChange;
import com.jcfk.eam.domain.query.base.EamFaultModeAssetQuery;
import com.jcfk.eam.domain.uploadExcel.main.EamAssetStatusChangeUploadExcel;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.jcfk.common.core.utils.IdUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.Date;

/**
 * 故障模式资产
 *
 * @author yrl
 * @email
 * @date 2024-12-02
 */
@Service
public class EamFaultModeAssetService extends BaseService<EamFaultModeAssetDao, EamFaultModeAsset> {

    /**
     * EamFaultModeAsset分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamFaultModeAssetDTO> queryByPage(DataPage<EamFaultModeAssetDTO> page, EamFaultModeAssetQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamFaultModeAsset是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamFaultModeAssetDTO dto) {
        QueryWrapper<EamFaultModeAsset> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入故障模式资产
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamFaultModeAssetDTO dto) {

        // 保存
        EamFaultModeAsset item = new EamFaultModeAsset();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新故障模式资产
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamFaultModeAssetDTO dto) {

        // 保存
        EamFaultModeAsset item = new EamFaultModeAsset();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除故障模式资产(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamFaultModeAssetDTO dto) {

        EamFaultModeAsset item = new EamFaultModeAsset();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamFaultModeAsset> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamFaultModeAsset item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取故障模式资产信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamFaultModeAssetDTO get(String id) {
        // 查询数据
        EamFaultModeAsset item = this.baseMapper.selectById(id);
        EamFaultModeAssetDTO dto = new EamFaultModeAssetDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamFaultModeAssetDTO>
     */
    public List<EamFaultModeAssetDTO> getList(EamFaultModeAssetQuery query) {
        // 查询条件
        Wrapper<EamFaultModeAsset> qw = Wrappers.<EamFaultModeAsset>query()
                .eq(query.getAssetKind() != null, "eamFaultModeAsset.asset_kind", query.getAssetKind())
                .eq(!StrUtil.isEmpty(query.getFaultModeId()), "eamFaultModeAsset.fault_mode_id", query.getFaultModeId())
                .eq(!StrUtil.isEmpty(query.getAssetTypeId()), "eamFaultModeAsset.asset_type_id", query.getAssetTypeId())
                .like(!StrUtil.isEmpty(query.getAssetTypeName()), "eamAssetType.asset_type_name", query.getAssetTypeName())
                .eq("eamFaultModeAsset.deleted", DeleteFlag.NOTDELETED.getCode())
                .eq("eamFaultModeAsset.enabled", AvailableStatus.ENABLE.getValue());
        // 查询数据
        return this.baseMapper.getList(qw);
    }
    /**
     * 插入资产状态变更记录
     *
     * @param list 批量插入资产状态变更记录
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(List<EamFaultModeAssetDTO> list) {

        EamFaultModeAssetDTO first = CollUtil.getFirst(list);
        String faultModeId = first.getFaultModeId();
        // 查询条件
        Wrapper<EamFaultModeAsset> qw = Wrappers.<EamFaultModeAsset>query()
                .eq("eamFaultModeAsset.fault_mode_id", faultModeId)
                .eq("eamFaultModeAsset.deleted", DeleteFlag.NOTDELETED.getCode())
                .eq("eamFaultModeAsset.enabled", AvailableStatus.ENABLE.getValue());
        // 查询数据
        List<EamFaultModeAssetDTO> existList = this.baseMapper.getList(qw);
        Map<String, String> existFaultModeAssetMap = existList.stream()
                .collect(Collectors.toMap(EamFaultModeAssetDTO::getAssetTypeId, EamFaultModeAssetDTO::getAssetTypeName));

        String existAsset = list.stream()
                .map(EamFaultModeAssetDTO::getAssetTypeId)
                .filter(existFaultModeAssetMap::containsKey)
                .map(existFaultModeAssetMap::get)
                .collect(Collectors.joining(","));
        if (StrUtil.isNotEmpty(existAsset)){
            throw new IllegalArgumentException(StrUtil.format("故障模式已存在资产类型:{}", existAsset));
        }
        List<EamFaultModeAsset> savelist = new ArrayList<>();
        list.forEach(itemOne -> {
            // 保存
            EamFaultModeAsset item = new EamFaultModeAsset();
            BeanUtils.copyProperties(itemOne, item);
            this.setDefaultValue(item);
            item.setEnabled(AvailableStatus.ENABLE.getValue());
            savelist.add(item);
        });
        // 保存
        if (savelist.size() > 0) super.saveBigBatch(savelist);
    }
    /**
     * 根据主键获取故障模式资产信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamFaultModeAsset item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

